<?php defined('SYSPATH') or die('No direct script access.');
require ('application/classes/dao/base.php');
class Controller_news extends Controller {

	public   function action_list()
	{

		try{
			$parm = get($this->request);
			if(!isset($parm['row']) ||!is_numeric($parm['row'])){
				$parm ['row'] = 11;
			}
			if(!isset($parm['start']) ||!is_numeric($parm['start'])){

				$parm ['start'] = 1;
			}
			if(!isset($parm['type']) ||$parm['type']==""){

				$parm ['type'] = "图文";
			}

		
			$result = DB::select('*')->from('sysnews')
			->where('type','=',$parm['type'])->offset(($parm['start']-1)*$parm['row'])->limit($parm['row'])->execute()->as_array();
			
		}catch(Exception $e){

			echo json_encode(error($e->getMessage()));
			exit;
		}
		$this->response->body( json_encode(success($result)));
	}
	public   function action_detail()
	{

		try{
			$parm = get($this->request);
			
			if(!isset($parm['id']) ||$parm['id']==""){
				redirect404();
			}
			//cho $parm['row'];
			$userId = 1;
			//$base->init(DB::);
			//$this->response->body('hello, world!');
			//$this->response->body('hello, world!');
			// print(get_include_path().PATH_SEPARATOR );
			//print_r($parm);
			$news = DB::select('*')->from('sysnews')->join('sysnews_detail')->on("sysnews_detail.id","=","sysnews.id")
                ->where("sysnews.id","=",$parm['id'])->execute()->as_array();
	
	  		if(count($news)==0){
	  			redirect404();
	  		}
			
			Database::instance()->begin();
			$query = DB::query(Database::SELECT, 'SELECT * FROM sysnews_look where id='.$parm['id'] .' and  userid='.$userId)->execute();

			if(count($query) == 0){
				$number = $news[0]['reading']+1;
				// print_r(array($parm['id'],$userId));
				DB::update("sysnews")->set(array('reading'=>$number))->where('id','=',$parm['id'])->execute();
				DB::insert("sysnews_look",array('id','userid'))->values(array($parm['id'],$userId))->execute();
			}
			Database::instance()->commit();

		}catch(Exception $e){
			Database::instance()->rollback();
			redirect404($e->getMessage());
		}
		$this->response->body( json_encode(success($news)));
	}
	public   function action_login()
	{
		echo 11;
	}
    public function action_save(){


        try{


            $user = checkSession(Session::instance());

            if($user == null) {
                throw new Exception("没有登陆");
            }
            $parm = get($this->request);

            if(!isset($parm['id'])||$parm['id'] == "" ){
                throw new Exception("帖子不存在，尝试刷新");
            }
            if(!isset($parm['content'])||$parm['content'] == "" ){
                throw new Exception("内容不能为空");
            }
            Database::instance()->begin();

            DB::insert("sysreply_news",array('newid','content','userId','parentId','user'))
                ->values(array($parm['id'],$parm['content'],$user['id'],$parm['parentId'],$user['user']))->execute();
            $query = DB::query(Database::UPDATE, 'update sysnews set replying=replying+1 where  id='.$parm['id'])->execute();

            Database::instance()->commit();
            echo json_encode(success("发布成功"));
        }catch(Exception $e){
            Database::instance()->rollback();
            echo json_encode(error($e->getMessage()));
        }
    }
    public function action_reply()
    {

    	$parm = get($this->request);
        $query = "";
       try{
           if (!isset($parm['id']) || $parm['id'] == "") {
                throw new Exception("帖子不存在，尝试刷新");
            }
           //echo 'SELECT sysreply_news.`user` ,sysuser_detail.photo,sysreply_news.content,sysreply_news.createDate,sysuser_detail.realname,reply.content as reply_content,reply.createDate as reply_createDate,reply.`user` as reply_user,replyuser.realname reply_realname,replyuser.photo as reply_photo FROM sysreply_news LEFT JOIN sysreply_news AS reply ON (reply.parentId = sysreply_news.id)left JOIN sysuser_detail replyuser ON (replyuser.`user` = reply.`user`) INNER JOIN sysuser_detail ON (sysuser_detail.`user` = sysreply_news.`user`)  where sysreply_news.newid='.$parm['id'];
//           $query = DB::query(Database::SELECT, )->execute();
           $query = DB::query(Database::SELECT, 'SELECT sysreply_news.id,sysreply_news.parentId, sysreply_news.`user` ,sysuser_detail.photo,sysreply_news.content,sysreply_news.createDate,sysuser_detail.realname,reply.content as reply_content,reply.createDate as reply_createDate,reply.`user` as reply_user,replyuser.realname reply_realname,replyuser.photo as reply_photo FROM sysreply_news LEFT JOIN sysreply_news AS reply ON (reply.parentId = sysreply_news.id)left JOIN sysuser_detail replyuser ON (replyuser.`user` = reply.`user`) INNER JOIN sysuser_detail ON (sysuser_detail.`user` = sysreply_news.`user`)  where  sysreply_news.newid='.$parm['id'].'  group by sysreply_news.id  order by id  limit '.$parm['start'].' ,'.$parm['row'])->execute()->as_array();

       }catch(Exception $e){
            echo json_encode(error($e->getMessage()));
           exit;
       }
        echo json_encode(success($query));
    }
} // End Welcome
